﻿using Hr.Orc.Client.Helper;
using Microsoft.Win32;
using System.Diagnostics;

using PModelOCR;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;


namespace Hr.Orc.Client
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow :Window
    {
        private SealStamp sealStamp;
        public MainWindow()
        {
            InitializeComponent();
            img_load.Visibility = Visibility.Hidden;
            content_text.IsReadOnly = true;
            sealStamp = new SealStamp();

            confidence_tb.Text = Convert.ToInt32((sealStamp.Confidence*100)).ToString();
            StartRotation();

        }
        private void StartRotation()
        {
            DoubleAnimation doubleAnimation = new DoubleAnimation(0, 360, TimeSpan.FromSeconds(3));
            doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;

            myRotateTransform.BeginAnimation(RotateTransform.AngleProperty, doubleAnimation);
        }

        private async void read_btn_Click(object sender, RoutedEventArgs e)
        {
            img_load.Visibility = Visibility.Visible;
            // 创建OpenFileDialog实例
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // 设置过滤器，例如仅选择文本文件
            openFileDialog.Filter = "PDF(*.pdf)|*.pdf|图像文件(*.bmp,*.jpg,*.png,*.jpge)|*.bmp;*.jpg;*.png;*.jpge";

            // 设置标题
            openFileDialog.Title = "选择文件";

            // 显示对话框
            bool? result = openFileDialog.ShowDialog();

            // 检查用户是否点击了"确定"按钮
            if (result == true)
            {
                string filePath = openFileDialog.FileName;
                string fileName = openFileDialog.SafeFileName;
                fileName = fileName.Replace(".", "_");
                if (content_text == null) return;
                lb_is_seal.Content = "";
                lb_filepath.Content = filePath;
                var CheckResult = await CheckImg(filePath, fileName);
                if (!CheckResult.Item2)
                {
                    lb_is_seal.Content = "未检测到印章";
                    lb_is_seal.Foreground = new SolidColorBrush(Colors.Red);
                }
                else
                {
                    lb_is_seal.Content = "存在印章";
                    lb_is_seal.Foreground = new SolidColorBrush(Colors.Green);
                }
                content_text.Text = CheckResult.Item1;
                //var bitmap = new BitmapImage(new Uri(CheckResult.Item3, UriKind.Absolute));
                //img_img.Height = img_img.Width / bitmap.Width * bitmap.Height;
                lstImgs.ItemsSource = CheckResult.Item3;
             /*   img_img.Source = bitmap;*/


            }
            img_load.Visibility = Visibility.Hidden;
        }


        public async Task<(string, bool, List<string>)> CheckImg(string filePath, string fileName)
        {
            var isSeal = false;
           
            string pdftext = string.Empty;
            List<string> imagePaths = new List<string>();
            await Task.Run(() =>
            {
                var dt = DateTime.Now;
                var myDocument = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                var directory = Path.Combine(myDocument, "OcrTempFile", dt.ToString("yyyy-MM-dd"), dt.ToString("HHmmss"));
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                var paths = filePath.Split(".");
                var fileType = paths[paths.Length - 1];
               
                if (fileType == "pdf")
                {
                    pdftext = ""; /*PdfHelper.PdfReadText(filePath);*/
                    if (string.IsNullOrEmpty(pdftext))
                    {
                        imagePaths = PdfHelper.PdfToImage(filePath, directory, 1);
                    }
                }
                else
                {
                    imagePaths.Add(filePath);
                }
                if (!imagePaths.Any())
                {
                    imagePaths = PdfHelper.PdfToImage(filePath, directory, 1);
                }
                if (string.IsNullOrEmpty(pdftext))
                {
                    Stopwatch stopwatch = Stopwatch.StartNew();
                    foreach (var item in imagePaths)
                    {

                        pdftext += POCRService.Instance.OCRImgeText(item);
                        /* pdftext += POCRService.Instance.OCRImgeText(item);

                        pdftext += OcrHelper.OCRImageToText(item);*/


                    }
                    stopwatch.Stop();
                    pdftext = "识别总时间:" + stopwatch.ElapsedMilliseconds + "ms,内容：" + pdftext;
                }
               /* foreach (var item in imagePaths)
                {
                    if (sealStamp.CheckHasSeal(item))
                    {
                        isSeal = true;
                        break;
                    }
                }*/
            });
            return (pdftext, isSeal, imagePaths);
        }

        private void seal_btn_Click(object sender, RoutedEventArgs e)
        {
            SealWindow sealWindow = new SealWindow(sealStamp.Confidence);
            sealWindow.Show();
        }

        private void TextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            int confidence = 0;
            if (!int.TryParse(confidence_tb.Text.Trim(), out confidence))
            {
                MessageBox.Show("请输入数字");
                confidence_tb.Text = "9";
                return;
            }
            if (confidence < 0 || confidence > 100)
            {
                MessageBox.Show("请输入0到100数字");
                confidence_tb.Text ="9";
                return;
            }
            sealStamp.Confidence = confidence / 100f;
        }

    }
}